package indi.qing.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import indi.qing.VO.LightControlVO;
import indi.qing.VO.SwitchControlVO;
import indi.qing.common.JWTUtils;
import indi.qing.common.Result;
import indi.qing.entity.Device;
import indi.qing.service.DeviceService;
import indi.qing.service.SubDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 熊卿智
 * @since 2021-12-15
 */
@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    @PostMapping("/switchControl")
    public Result switchControl(@RequestBody SwitchControlVO switchControlVO) {
        try {
            boolean succ = deviceService.switchControl(switchControlVO.getState(), switchControlVO.getDeviceId());
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
        return Result.ok("下发成功");
    }

    @PostMapping("/lightControl")
    public Result LightControl(@RequestBody LightControlVO lightControlVO) {
        try {
            if (lightControlVO.getLuminance() < 0) {
                return Result.failed("亮度不能小于0");
            }
            if (lightControlVO.getLuminance() > 100) {
                return Result.failed("亮度不能大于100");
            }
            boolean succ = deviceService.LightControl(lightControlVO.getLuminance(), lightControlVO.getDeviceId());
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
        return Result.ok("下发成功");
    }

    @PostMapping("/getDevices")
    public Result getDevices(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = Long.valueOf(JWT.decode(token).getClaim("userId").asString());
        try {
            List<Device> devices = deviceService.getDevices(userId);
            return Result.ok(devices);
        }catch (Exception e){
            return Result.failed(e.getMessage());
        }
    }

}

